package com.beyond.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

public class FileUtil {
	
	FileUtil fileUtil = null;
	
	public FileUtil(){}
	
	public FileUtil getFileUtil(){
		FileUtil fileObj = null;
		if(fileUtil == null)
			fileObj = new FileUtil();
		else
			fileObj = fileUtil;
		
		return fileObj;
	}

	public static void createFile(String dir,String fileContent) throws Exception{
		File myfile = new File(dir);
		try {
			if(!myfile.exists())
				myfile.createNewFile();
			else{
				myfile.delete();
				myfile.createNewFile();
			}
			
			System.out.println("File Path is "+dir);
			System.out.println("Ready create file");
			FileWriter resultFile = new FileWriter(myfile);
			PrintWriter myNewFile = new PrintWriter(resultFile);
			myNewFile.println(fileContent);
			System.out.println("Create finish");
			resultFile.close();
		} catch (IOException e) {
			System.out.println("无法创建文件！");
			e.printStackTrace();
		}
	}
	
	/**
	 * delete filefolder
	 * @param dir
	 */
	public static void delFile(String dir){
		File file = new File(dir);
		file.delete();
	}
	
	public static void createFolder(String dir){
		File file = new File(dir);
		if(!file.exists())
			file.mkdir();
	}
	
	/**
	 * 获取属性文件的值
	 * @param name
	 */
	public String getPropertyVal(String name){
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
		Properties p = new Properties();
		try {
			p.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return p.getProperty(name);
	}
	
	/**
	 * 获取resource.properties 文件的内容
	 * @param name
	 * @return
	 */
	public String getResourceVal(String name){
		InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("config.properties");
		Properties p = new Properties();
		try {
			p.load(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return p.getProperty(name);
	}
	
	public static void main(String[] args) {
		String dir = "c:\\abc.sql";
		String fileContent = "abccddddd//dd//ddddd";
		
		FileUtil file = new FileUtil();
		try {
			
//			createFile(dir, fileContent);
			String name = "jdbc.driverClassName";
			System.out.println(file.getPropertyVal(name));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
